package com.example.sherlockzhong.plush_v2.MapUtils;

/**
 * Created by SherlockZhong on 8/28/14.
 */
public class LocationsUtil {

    public static double getDistance(double currentLon, double currentLat, double targetLon, double targetLat) {
        double PI = 3.14159265359;
        double PI_DOUBLE = 6.28318530712;
        double PI_HALF = 0.01745329252;
        double R_EARTH = 6370693.5;

        double myew, myns, ew2, ns2;
        double dx, dy, dew;
        double distance;
        myew = currentLon * PI_HALF;
        myns = currentLat * PI_HALF;
        ew2 = targetLon * PI_HALF;
        ns2 = targetLat * PI_HALF;
        dew = myew - ew2;
        if (dew > PI) {
            dew = PI_DOUBLE - dew;
        } else if (dew < -PI) {
            dew = PI_DOUBLE + dew;
        }
        dx = R_EARTH * Math.cos(myns) * dew;
        dy = R_EARTH * (myns - ns2);
        distance = Math.sqrt(dx * dx + dy * dy);
        return distance;
    }

    public static Coordinate getNearest(double lon, double lat) {
        double nearestDistance = -1.0;
        double currentDistance;
        Coordinate nearest = null;
        Coordinate[] locations = CoordinateConstant.getAllAsArray();
        for (int i = 0; i < locations.length; i++) {
            currentDistance = getDistance(lon, lat, locations[i].lon, locations[i].lat);
            if ((nearestDistance == -1.0 || currentDistance < nearestDistance) && currentDistance < 2000) {
                nearestDistance = currentDistance;
                nearest = locations[i];
            }
        }
        return nearest;
    }

}
